﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using GMap.NET;
using GMap.NET.MapProviders;
using Common;
using Model;
using GMap.NET.WindowsForms;
using System.Linq;

namespace TaxiDispatchClient
{
    public partial class CallForTaxiForm : DevExpress.XtraEditors.XtraForm
    {
        public CallForTaxiForm()
        {
            InitializeComponent();          
        }
        //87
        private DataTable _dtTaxiList;
        private Thread t;
        private readonly GMapControl _gMap = new GMapControl();

        private Socket _sendtoTransferServer;

        public CallForTaxiForm(DataTable taxilist)
        {
            InitializeComponent();          
            _dtTaxiList = taxilist.Copy();
            _dtTaxiList.Rows.Clear();
            foreach (DataRow row in taxilist.Rows)
            {
                int carType = int.Parse(row["车辆类型"].ToString());
                if (carType == ConstParameters.CarTypeOfTaxi)
                {
                    _dtTaxiList.Rows.Add(row.ItemArray);
                }
            }
            gridControl_TaxiList.DataSource = _dtTaxiList;
            gridView1.GroupPanelText = "当前一共" + _dtTaxiList.Rows.Count + "辆出租车.    " + DateTime.Now;
            _gMap.MapProvider = GMapProviders.GoogleChinaMap;


        }

        private void simpleButton_goto_Click(object sender, EventArgs e)
        {
            GeoCoderStatusCode status = _gMap.SetPositionByKeywords(textBoxGeo.Text);
            if (status != GeoCoderStatusCode.G_GEO_SUCCESS)
            {
                MessageBox.Show("Google Maps Geocoder can't find: '" + textBoxGeo.Text + "', reason: " + status.ToString(), "GMap.NET", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                int distance = int.Parse(radioGroup_Distant.EditValue.ToString());
                List<TaxiInfo> taxiInfos = MainForm.PositionService.GetNearbyGps(_gMap.Position.Lng, _gMap.Position.Lat, distance, Common.ConstParameters.TypeTaxiDispatchClient);
                _dtTaxiList.Clear();
                foreach (TaxiInfo taxiInfo in taxiInfos)
                {
                    DataRow dr = _dtTaxiList.NewRow();
                    dr["司机姓名"] = taxiInfo.DriverName;
                    dr["出租车牌照"] = taxiInfo.TaxiNo;
                    dr["司机号码"] = taxiInfo.DriverPhoneNumber;
                    dr["出租车状态"] = OperateAgreement.GetTaxiState(taxiInfo.TaxiState);
                    dr["出租车车型"] = taxiInfo.TaxiType;
                    dr["经度"] = taxiInfo.Latitude;
                    dr["纬度"] = taxiInfo.Longitude;
                    dr["所属公司"] = taxiInfo.Remark;
                    dr["数据更新时间"] = taxiInfo.UpdateTime.ToString("HH:mm:ss");
                    dr["IP地址"] = taxiInfo.Ip;
                    dr["出租车ID"] = taxiInfo.Id;
                    _dtTaxiList.Rows.Add(dr);
                }
                gridControl_TaxiList.DataSource = _dtTaxiList;
                gridView1.GroupPanelText = "当前一共" + _dtTaxiList.Rows.Count + "辆出租车.    " + DateTime.Now.ToString();

            }
        }

        private void simpleButton_Select_Click(object sender, EventArgs e)
        {
            string parameter;
            string parameterVaule = textEdit_condition.Text;
            if (radioGroup_SelectType.SelectedIndex == 0)
            {
                parameter = "出租车牌照";
            }
            else if (radioGroup_SelectType.SelectedIndex == 1)
            {
                parameter = "出租车车型";
            }
            else
            {
                if (textEdit_condition.Text.Trim() == "")//**********新加未测
                {
                    return;
                }
                parameter = "所属公司";
            }

            if (_dtTaxiList.Rows.Count == 0)
            {
                GetAllTaxiList();
            }


            _dtTaxiList.DefaultView.RowFilter = parameter + " like '%" + parameterVaule + "%'";
            gridControl_TaxiList.DataSource = _dtTaxiList.DefaultView;
            gridView1.GroupPanelText = "当前一共" + _dtTaxiList.DefaultView.Count + "辆出租车.    " + DateTime.Now;
        }

        private void simpleButton_GetAll_Click(object sender, EventArgs e)
        {
            GetAllTaxiList();
            gridControl_TaxiList.DataSource = _dtTaxiList;
            gridView1.GroupPanelText = "当前一共" + _dtTaxiList.Rows.Count + "辆出租车.    " + DateTime.Now;

        }


        private void GetAllTaxiList()
        {
            try
            {
                List<TaxiInfo> taxiInfos = MainForm.PositionService.GetAllTaxiInfos();

                _dtTaxiList.Clear();
                _dtTaxiList.DefaultView.RowFilter = "";
                foreach (TaxiInfo taxiInfo in taxiInfos)
                {
                    if (taxiInfo.TaxiState == 0)
                    {
                        DataRow dr = _dtTaxiList.NewRow();
                        dr["司机姓名"] = taxiInfo.DriverName;
                        dr["出租车牌照"] = taxiInfo.TaxiNo;
                        dr["司机号码"] = taxiInfo.DriverPhoneNumber;
                        dr["出租车状态"] = OperateAgreement.GetTaxiState(taxiInfo.TaxiState);
                        dr["出租车车型"] = taxiInfo.TaxiType;
                        dr["经度"] = taxiInfo.Latitude;
                        dr["纬度"] = taxiInfo.Longitude;
                        dr["所属公司"] = taxiInfo.Remark;
                        dr["数据更新时间"] = taxiInfo.UpdateTime.ToString("HH:mm:ss");
                        dr["IP地址"] = taxiInfo.Ip;
                        dr["出租车ID"] = taxiInfo.Id;
                        _dtTaxiList.Rows.Add(dr);
                    }

                }
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
            }

        }

        //private void SendSms_FormClosed(object sender, FormClosedEventArgs e)
        //{
        //    if (_smsMessageBox != null)
        //    {
        //        _smsMessageBox.Close();
        //    }
        //}

        private void simpleButton_SendToTaxi_Click(object sender, EventArgs e)
        {
            if (textEdit_phonenum.Text.Trim() == "")
            {
                XtraMessageBox.Show("请输入招车客户手机号码！");
                textEdit_phonenum.Focus();
                return;
            }
            btn_sendToTaxi.Enabled = false;
            btn_sendSMS.Enabled = false;


            try
            {
                string transferServerIP = OperateConfig.GetClientTransferServerIp();
                IPAddress ipAddress = IPAddress.Parse(transferServerIP);
                _sendtoTransferServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint address = new IPEndPoint(ipAddress, ConstParameters.TransferListenPort);
                _sendtoTransferServer.NoDelay = true;
                _sendtoTransferServer.Connect(address);
            }
            catch (Exception ex)
            {
                btn_sendToTaxi.Enabled = true;
                btn_sendSMS.Enabled = true;
                CommonRoutine.HandlingExceptions(ex, true);
                return;
            }
            t = new Thread(SendMessageToTaxi);
            t.Start();

            //for (int i = 0; i < gridView1.RowCount; i++)
            //{

            //    DataRow dr = gridView1.GetDataRow(i);
            //    if (dr["出租车状态"].ToString() == "空载")
            //    {

            //    }

            //}
        }


        private void SendMessageToTaxi()
        {
            try
            {

                Dictionary<string, byte[]> phoneNuber_sendData = new Dictionary<string, byte[]>();
                bool isSomeOneTaxiAnswer = false;
                byte[] phoneNumberBytes = CommonRoutine.BcdStringToBytes(textEdit_phonenum.Text.PadLeft(12, '0'));
                for (int i = 0; i < gridView1.RowCount; i++)
                {
                    DataRow dr = gridView1.GetDataRow(i);
                    if (dr["出租车状态"].ToString() == "空载")
                    {
                        string phoneNumber = dr["司机号码"].ToString();
                        string strCommand = memoEdit_SendSms.Text;
                        IPAddress localIp = ((IPEndPoint)(_sendtoTransferServer.LocalEndPoint)).Address;
                        List<byte> mBytes = new List<byte>();

                        mBytes.AddRange(BitConverter.GetBytes(ConstParameters.CmdSendSmsToTaxi).Reverse());
                        mBytes.AddRange(CommonRoutine.BcdStringToBytes(phoneNumber.PadLeft(12, '0')));

                        mBytes.AddRange(localIp.GetAddressBytes());
                        mBytes.Add(4);


                        string datestring = DateTime.Now.ToString("yyyyMMddHHmmss");

                        mBytes.AddRange(CommonRoutine.BcdStringToBytes(datestring));

                        mBytes.AddRange(Encoding.GetEncoding("GBK").GetBytes(strCommand));
                        byte[] messageBody = mBytes.ToArray();


                        byte[] messageHead = OperateAgreement.GetMessageHead(ConstParameters.CmdRetweetTaxiDispatchClient, false, false, messageBody.Length, phoneNumberBytes, new byte[2], 0, 0);
                        byte[] sendData = OperateAgreement.PackageSendData(messageHead, messageBody);
                        //Thread.Sleep(300);
                       // _sendtoTransferServer.Send(sendData);
                        _sendtoTransferServer.Send(sendData);
                   
                        phoneNuber_sendData.Add(phoneNumber, sendData);
                    }
                }

                List<byte> receBufferBb = new List<byte>();

                DateTime sendTime = DateTime.Now;
                List<string> phoneNumber_List = new List<string>();

                while (true)
                {
                    #region retrySend
                    DateTime now = DateTime.Now;
                    TimeSpan timeSpan = new TimeSpan(now.Ticks - sendTime.Ticks);
                    if (timeSpan.TotalSeconds > 15)
                    {
                        foreach (KeyValuePair<string, byte[]> keyValuePair in phoneNuber_sendData)
                        {
                            if (!phoneNumber_List.Contains(keyValuePair.Key))
                            {
                                _sendtoTransferServer.Send(keyValuePair.Value);
                            }
                        }
                        Thread.Sleep(1000);

                    }
                    #endregion

                    #region rece Data
                    try
                    {
                        byte[] receBuffer = new byte[100];
                        int receDataLength = _sendtoTransferServer.Receive(receBuffer);
                        Thread.Sleep(1);
                        byte[] temp = new byte[receDataLength];
                        Array.Copy(receBuffer, 0, temp, 0, temp.Length);
                        receBufferBb.AddRange(temp);
                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex);
                    }
                    #endregion
                    int receBufferBBindex = 0;
                    int sendflag = -1;
                    int endindex = 0;
                    List<byte> receByteList = new List<byte>();






                    foreach (byte b in receBufferBb)
                    {
                        receBufferBBindex++;
                        if (b == 0x7e) sendflag++;
                        if (sendflag >= 0)
                        {
                            if (sendflag == 0) { receByteList.Add(b); }
                            else if (sendflag == 1)
                            {
                                receByteList.Add(b);
                                byte[] receData = receByteList.ToArray();
                                receByteList.Clear();
                                sendflag = -1;
                                endindex = receBufferBBindex;
                                #region
                                byte[] realData = OperateAgreement.RestoreReceData(receData);
                                if (OperateAgreement.JudgeisCompleteData(realData))
                                {
                                    ushort messageId = OperateAgreement.GetMessageIdInMessageHead(realData);
                                    string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);

                                    phoneNumber_List.Add(phoneNumber);

                                    if (messageId == ConstParameters.CmdSendSmsToTaxiReply)
                                    {
                                        if (!isSomeOneTaxiAnswer)
                                        {
                                            isSomeOneTaxiAnswer = true;
                                            DataRow[] drs = _dtTaxiList.Select("司机号码=" + phoneNumber);
                                            if (drs.Length > 0)
                                            {
                                                DataRow dr = drs[0];
                                                string driverName = dr["司机姓名"].ToString();
                                                string taxiNo = dr["出租车牌照"].ToString();
                                                string taxiType = dr["出租车车型"].ToString();

                                                TradeInfo tradeInfo = new TradeInfo();
                                                tradeInfo.PhoneNumber = textEdit_phonenum.Text;
                                                tradeInfo.PhoneNumber2 = phoneNumber;
                                                tradeInfo.TradeTime = DateTime.Now;
                                                tradeInfo.Type = 2; // Said platform call for car
                                                MainForm.PositionService.AddTradeInfo(tradeInfo);
                                                this.BeginInvoke(new MethodInvoker(delegate()
                                                                                       {
                                                                                           //btn_sendToTaxi.Enabled = true;
                                                                                           btn_sendSMS.Enabled = true;
                                                                                           string ss = "司机姓名 :" +
                                                                                                       driverName +
                                                                                                       "，牌照: " +
                                                                                                       taxiNo +
                                                                                                       "，出租车车型: " +
                                                                                                       taxiType +
                                                                                                       "，司机号码：" +
                                                                                                       phoneNumber + "," +
                                                                                                       "正前往你的招车地点。";
                                                                                           memoEdit_SendSmsTo.Text = ss;
                                                                                       }));
                                                List<byte> mBody = new List<byte>();

                                                mBody.AddRange(
                                                    BitConverter.GetBytes(ConstParameters.CmdTaxiResponseSuccess).
                                                        Reverse());
                                                mBody.AddRange(
                                                    CommonRoutine.BcdStringToBytes(phoneNumber.PadLeft(12, '0')));

                                                mBody.Add(1);

                                                //----------------------no Ip in data
                                                byte[] mHead =
                                                    OperateAgreement.GetMessageHead(
                                                        ConstParameters.CmdRetweetTaxiDispatchClientNoipInData, false, false,
                                                        mBody.ToArray().Length, phoneNumberBytes, new byte[2], 0, 0);
                                                byte[] sendData1 = OperateAgreement.PackageSendData(mHead,
                                                                                                    mBody.ToArray());
                                                try
                                                {
                                                    _sendtoTransferServer.Send(sendData1);
                                                }
                                                catch (Exception ex)
                                                {
                                                    CommonRoutine.HandlingExceptions(ex);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            List<byte> mBody = new List<byte>();

                                            mBody.AddRange(BitConverter.GetBytes(ConstParameters.CmdTaxiResponseSuccess).Reverse());
                                            mBody.AddRange(CommonRoutine.BcdStringToBytes(phoneNumber.PadLeft(12, '0')));

                                            mBody.Add(2);
                                            //----------------------no Ip in data
                                            byte[] mHead = OperateAgreement.GetMessageHead(ConstParameters.CmdRetweetTaxiDispatchClientNoipInData, false, false, mBody.ToArray().Length, phoneNumberBytes, new byte[2], 0, 0);
                                            byte[] sendData1 = OperateAgreement.PackageSendData(mHead, mBody.ToArray());
                                            try
                                            {
                                                _sendtoTransferServer.Send(sendData1);

                                            }
                                            catch (Exception ex)
                                            {
                                                CommonRoutine.HandlingExceptions(ex);
                                            }
                                        }


                                    }


                                }
                                #endregion
                            }
                        }
                    }
                    if (endindex > 0)
                    {
                        receBufferBb.RemoveRange(0, endindex);
                    }



                }
                //   DataRow dr = (DataRow)objdr;


                //  sendtoTransferServer.Close();
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
            }
        }

        private void simpleButton_SendSms_Click(object sender, EventArgs e)
        {
            if (textEdit_phonenum.Text.Trim() == "")
            {
                XtraMessageBox.Show("请输入招车客户手机号码！");
                textEdit_phonenum.Focus();
                return;
            }
            labelControl_SmsResult.Text = "发送中。。。。。。";
            int smsid = MainForm.PositionService.SendSms(textEdit_phonenum.Text, memoEdit_SendSmsTo.Text);
            Thread t = new Thread(QuerySmsState);
            t.Start(smsid);

        }

        private void QuerySmsState(object obj)
        {
            int smsid = int.Parse(obj.ToString());
            bool result = false;
            while (!result)
            {
                result = MainForm.PositionService.SmsQuery(smsid);
                Thread.Sleep(1000);
            }
            BeginInvoke(new MethodInvoker(delegate()
                                                   {
                                                       labelControl_SmsResult.Text = "发送成功。";
                                                       btn_sendSMS.Enabled = true;
                                                   }));
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;
            Cursor = Cursors.Arrow;
        }
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Close();
        }


        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void CallForTaxiForm_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        private void CallForTaxiForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (t != null) t.Abort();
                _sendtoTransferServer.Shutdown(SocketShutdown.Both);
                _sendtoTransferServer.Close();
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
            }
        }

        private void textEdit_phonenum_Enter(object sender, EventArgs e)
        {
            ImeMode = ImeMode.KatakanaHalf;
            InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(CultureInfo.GetCultureInfo("en-US"));
        }

        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }
       
    }
}